package com.konglz.publisher.confirm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description
 * @Author konglz
 * @Data 2023/5/12 14:21
 */
@Component
@Slf4j
public class ExchangeConfirmCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @Description: 在模板类初始化的时候设置确认消息的回调
     * @return: void
     * @Author: konglz
     * @Date: 2023/5/12
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            //消息发送成功
            log.info("消息发送成");
        } else {
            //消息发送失败
            String content = new String(correlationData.getReturnedMessage().getBody());
            System.out.println("消息发送失败，消息是:" + content);
            //失败逻辑
        }
    }

    /**
    * @Description: 消息发送失败，会执行
    * @return: void
    * @Author: konglz
    * @Date: 2023/5/12
    */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("消息回退");
    }
}
